package org.example.chat.websocket.entity;

import cn.hutool.json.JSONUtil;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.example.chat.entity.Group;
import org.example.chat.service.IGroupService;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户id和channel的映射关系, 该类不允许创建对象
 * @author cheval
 */
@Component
public class ChannelContext {

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private IGroupService groupService;
    private String messageQueue = "chat-message-topic";


    /**
     * 存放用户id和channel映射关系, 用户握手建立好连接之后，就建立映射关系
     */
    private static Map<String, Channel> mapping = new ConcurrentHashMap<>();

    /**
     * 存放群id的在线用户的的channel映射关系， 每个用户握手建立好之后，就加入到对应的channelgroup中，方便集中发送消息，如果不使用
     * channalgroup,还需要循环遍历mapping,判断然后一个一个发送，效率低。
     */
    private static Map<String, ChannelGroup> groupMapping = new HashMap<>();

    public static Channel getChannel(String userId) {
        return mapping.get(userId);
    }

    public static void addMapping(String userId, Channel channel) {
        mapping.put(userId,channel);
    }

    public static void removeMapping(String userId) {
        mapping.remove(userId);
    }

    /**
     * 给channel绑定用户id属性, 方便使用
     */
    private void channelBindUserId(Channel channel, String userId) {
        // 1. 创建AttributeKey
        String channelId = channel.id().toString();
        AttributeKey<String> key = AttributeKey.valueOf(channelId);
        if (key == null) {
            key = AttributeKey.newInstance(channelId);
        }
        // 2. 设置到channel属性上
        channel.attr(key).set(userId);
    }


    /**
     * 用户channel加入到用户已添加的群组中
     * @param channel
     * @param userId
     */
    private void channelAdd2ChannelGroup(Channel channel, String userId) {
        // 1. 从数据库中获取用户所加群组， 这里也可以从缓存中获取，但是考虑登录操作不频繁，而且不想依赖redisTemplate,所以就直接从数据库获取了
        List<Group> groups = groupService.getUserGroupsById(userId);
        // 2. 遍历群组，将用户channel加入到各群组的channelGroup中
        if (groups == null || groups.size() == 0) {
            return;
        }
        ChannelGroup channelGroup = null;
        for (Group group : groups) {
            // 判断群组的channelGroup是否已经存在
            channelGroup = groupMapping.get(group.getId());
            if (channelGroup == null) {
                channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
                groupMapping.put(group.getId(), channelGroup);
            }
            // 用户channel添加到channelGroup
            channelGroup.add(channel);
        }
    }

    public void initChannelContext(Channel channel, String userId) {
        // 1. channel绑定userID
        channelBindUserId(channel, userId);
        // 2. channel和userId建立映射
        mapping.put(userId, channel);
        // 3. 用户channel加入到用户已添加的群组中
        channelAdd2ChannelGroup(channel, userId);
    }


    public void destroy(Channel channel) {
        // 获取与channel绑定的userId
        String channelId = channel.id().toString();
        AttributeKey<String> key = AttributeKey.valueOf(channelId);
        if (key != null) {
            String userId = channel.attr(key).get();
            // 移除用户和channel的映射关系
            mapping.remove(userId);
            // 从用户所在群组中移除当前用户的channel, 这一步无需手动操作， 当channel断开连接后，channelGroup会自动移除channel
        }
        // 关闭连接
        channel.close();
    }

    /**
     * 启动的时候监听消息队列里的消息
     */
    @PostConstruct
    public void startListen() {
        redissonClient.getTopic(messageQueue).addListener(QueueMessage.class, new MessageListener<QueueMessage<MessagePack>>() {
            @Override
            public void onMessage(CharSequence topicName, QueueMessage<MessagePack> msg) {
                QueueMessage.Type type = msg.getType();
                String receiverId = msg.getReceiverId();
                switch (type) {
                    case SIGNAL:
                        Channel channel = mapping.get(receiverId);
                        if(channel != null) {
                            channel.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(msg)));
                        }
                        break;
                    case GROUP:
                        ChannelGroup channelGroup = groupMapping.get(receiverId);
                        if (channelGroup != null) {
                            channelGroup.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(msg.getMsg())));
                        }
                        break;
                    default:
                }
            }
        });
    }


    /**
     * 发送消息到指定用户
     * @param receiverId 接收者id
     * @param message   发送的消息
     */
    public void send(String receiverId, MessagePack message, QueueMessage.Type type) {
        QueueMessage<MessagePack> queueMessage = new QueueMessage<MessagePack>(receiverId, message, type);
        // 1. 先在本服务查询用户对应channel, 如果没有则发送到其他集群，让其他集群查询自己的mapping，找到后发送消息
        switch (type) {
            case SIGNAL:
                Channel channel = mapping.get(receiverId);
                if (channel == null) {
                    // 发布到消息队列
                    redissonClient.getTopic(messageQueue).publish(queueMessage);
                } else {
                    // 直接发送
                    channel.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(message)));
                }
                break;
            case GROUP:
                ChannelGroup channelGroup = groupMapping.get(receiverId);
                if (channelGroup == null) {
                    // 发布到消息队列
                    redissonClient.getTopic(messageQueue).publish(queueMessage);
                } else {
                    // 直接发送
                    channelGroup.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(message)));
                }
                break;
            default:
        }
    }
}
